<template>
<div class="base-container">
  <t-row :gutter="14">
    <t-col :span="9">
      <t-card class="step-card" title="个人信息" size="small">
                  <t-form  ref="form" :colon="true"  class="step-form" @submit="updateUserProfile" :data="formData" :rules="rules"
                          labelWidth="180px">
                    <t-row>
                      <t-col :span="6">
                        <t-form-item label="登录账号" name="userName">
                          <t-input disabled clearable style="width: 390px" v-model="formData.userName"></t-input>
                        </t-form-item>
                      </t-col>
                      <t-col :span="6">
                        <t-form-item label="角色" name="roleIds">
                          <t-input disabled style="width: 390px" multiple placeholder="请选择角色"  v-model="formData.roleIds">
                          </t-input>
                        </t-form-item>
                      </t-col>
                    </t-row>
                    <t-row>
                      <t-col :span="6">
                        <t-form-item label="真实姓名" name="nickName">
                          <t-input clearable style="width: 390px" v-model="formData.nickName"></t-input>
                        </t-form-item>
                      </t-col>
                      <t-col :span="6">
                        <t-form-item label="性别" name="sex">
                          <t-select clearable placeholder="请选择性别" filterable style="width: 390px" :options="dict.type.sys_user_sex"  v-model="formData.sex">
                          </t-select>
                        </t-form-item>
                      </t-col>
                    </t-row>
                    <t-row>
                      <t-col :span="6">
                        <t-form-item label="身份证号" name="idCard">
                          <t-input style="width: 390px" @change="onIdCardChange" placeholder="请输入身份证号" clearable v-model="formData.idCard"
                          ></t-input>
                        </t-form-item>
                      </t-col>
                      <t-col :span="6">
                        <t-form-item label="生日" name="birthDate">
                          <t-date-picker disabled clearable placeholder="请选择生日"  style="width: 390px"
                                         v-model="formData.birthDate"></t-date-picker>
                        </t-form-item>
                      </t-col>
                    </t-row>
                    <t-row>
                      <t-col :span="6">
                        <t-form-item label="民族" name="national">
                          <t-select clearable placeholder="请选择" filterable style="width: 390px" :options="dict.type.national"  v-model="formData.national">
                          </t-select>
                        </t-form-item>
                      </t-col>
                      <t-col :span="6">
                        <t-form-item label="政治面貌"  name="politicsStatus">
                          <t-select filterable style="width: 390px" v-model="formData.politicsStatus" clearable placeholder="请选择政治面貌" :options="dict.type.politics_status">
                          </t-select>
                        </t-form-item>
                      </t-col>
                    </t-row>
                    <t-row>
                        <t-col :span="6">
                          <t-form-item label="工作单位" name="departmentId">
                            <t-input clearable disabled style="width: 390px" v-model="formData.dept.deptName"  placeholder="请输入单位"></t-input>
                          </t-form-item>
                        </t-col>
                      <t-col :span="6">
                        <t-form-item label="通讯地址" name="contactAds">
                          <t-input clearable  style="width: 390px" v-model="formData.contactAds"  placeholder="请输入通讯地址"></t-input>
                        </t-form-item>
                      </t-col>
                    </t-row>
                    <t-row>
                      <t-col :span="6">
                        <t-form-item label="手机号" name="phonenumber">
                          <t-input clearable style="width: 390px" v-model="formData.phonenumber"></t-input>
                        </t-form-item>
                      </t-col>
                      <t-col :span="6">
                        <t-form-item label="邮箱" name="email">
                          <t-input clearable style="width: 390px" v-model="formData.email"></t-input>
                        </t-form-item>
                      </t-col>
                    </t-row>
                    <t-row>
                      <t-col :span="6">
                        <t-form-item label="学校" name="school">
                          <t-input clearable style="width: 390px" v-model="formData.school"  placeholder="请输入学校"></t-input>
                        </t-form-item>
                      </t-col>
                      <t-col :span="6">
                        <t-form-item label="专业" name="majorName">
                          <t-input clearable style="width: 390px" v-model="formData.majorName"  placeholder="请输入专业"></t-input>
                        </t-form-item>
                      </t-col>
                    </t-row>
                    <t-row>
                      <t-col :span="6">
                        <t-form-item label="学历" name="education">
                          <t-select style="width: 390px" v-model="formData.education" clearable placeholder="请选择学历"
                                    :options="dict.type.education">
                          </t-select>
                        </t-form-item>
                      </t-col>

                      <t-col :span="6">
                        <t-form-item label="学位" name="degree">
                          <t-select clearable placeholder="请选择学位" filterable style="width: 390px" :options="dict.type.degree"  v-model="formData.degree">
                          </t-select>
                        </t-form-item>
                      </t-col>
                    </t-row>

                    <t-row>
                      <t-col :span="6">
                        <t-form-item label="现从事专业" name="majorNowName">
                          <t-input clearable style="width: 390px" v-model="formData.majorNowName"  placeholder="请输入专业"></t-input>
                        </t-form-item>
                      </t-col>
                        <t-col :span="6">
                          <t-form-item label="微信号" name="wechat">
                            <t-input clearable style="width: 390px" v-model="formData.wechat"></t-input>
                          </t-form-item>
                        </t-col>
                    </t-row>
                    <t-row>
                      <t-col :span="6">
                                      <t-form-item  label="技术职称" name="profTitId">
                                        <t-tree-select clearable @change="onProfTitIdChange" filterable style="width: 390px" :treeProps="{keys: {value: 'id'}, valueMode: 'onlyLeaf'}"
                                                       v-model="formData.profTitId" :data="profTitOptions"
                                                       placeholder="请选择技术职称"></t-tree-select>
                                      </t-form-item>
                      </t-col>
                      <t-col :span="6">
                        <t-form-item label="职称" name="profTit">
                          <t-select disabled clearable style="width: 390px" v-model="formData.profTit"
                                    :options="dict.type.prof_tit">
                          </t-select>
                        </t-form-item>
                      </t-col>
                    </t-row>
                    <t-row>
                      <t-col :span="6">
                        <t-form-item label="职务" name="duty">
                          <t-input clearable style="width: 390px" v-model="formData.duty"  placeholder="请输入职务"></t-input>
                        </t-form-item>
                      </t-col>
                      <t-col :span="6">
                        <t-form-item label="邮编" name="postcode">
                          <t-input clearable style="width: 390px" v-model="formData.postcode"  placeholder="请输入"></t-input>
                        </t-form-item>
                      </t-col>
                    </t-row>
                    <t-row>
                      <t-col :span="12">
                        <t-form-item clearable label="个人简介" name="remark">
                          <t-textarea
                            clearable
                            :autosize="{minRows: 5}"
                            v-model="formData.remark"
                            placeholder="请输入内容"
                          />
                        </t-form-item>
                      </t-col>
                    </t-row>

                    <div class="btn-group-inline" style="justify-content: end">
                    <t-button theme="primary"  type="submit">保存</t-button>
                    <t-button theme="default" variant="outline" type="reset">重置</t-button>
                    </div>
                  </t-form>
      </t-card>
      <t-card class="step-card" title="安全设置" size="small">
                <div style="padding: 20px 0px 20px 0px">
                  <t-row style="height: 83px;border-bottom: 1px solid rgb(229,230,235)" align="stretch">
                    <t-col style="display: flex;justify-content: center;align-items: center;font-weight: 500" :span="1">登录密码</t-col>
                    <t-col style="display: flex;justify-content: flex-start;align-items: center;" :span="5">
                      8-20 个字符，需同时包含数字、大小写字母以及特殊符号
                      <div> <t-button @click="dialog.header='重置密码';dialog.open=true" variant="text"
                                      class="t-button-link">
                        <t-icon name="edit-1" slot="icon"/>
                        修改
                      </t-button></div>
                    </t-col>
                  </t-row>
        <!--          <t-row style="height: 83px;border-bottom: 1px solid rgb(229,230,235)" align="stretch">-->
        <!--            <t-col style="display: flex;justify-content: center;align-items: center;font-weight: 500" :span="1">微信登录</t-col>-->
        <!--            <t-col style="display: flex;justify-content: flex-start;align-items: center;" :span="5">-->
        <!--              授权后可登录-->
        <!--              <div> <t-button @click="dialog.header='微信绑定';dialog.openBind=true" variant="text"-->
        <!--                              class="t-button-link">-->
        <!--                <t-icon name="logo-wechat" slot="icon"/>-->
        <!--                绑定-->
        <!--              </t-button></div>-->
        <!--            </t-col>-->
        <!--          </t-row>-->
                </div>
      </t-card>
    </t-col>
    <t-col :span="3">
      <t-card class="user-intro step-card" :bordered="false">
        <t-avatar v-if="formData.avatar" size="100px" :image="formData.avatar">
        </t-avatar>
        <t-avatar v-else size="100px">
          {{formData.nickName}}
        </t-avatar>
        <file-upload  @success="onAvatar" accept="image/*" v-model="avatarFileIds" moduleKey="avatar"
                     :fileList="avatarFileLists"
                      tips="">
          <template #fileListDisplay><div></div></template>
          <t-icon style="position: absolute;top:120px;left:120px;color: var(--td-brand-color);z-index: 10;background-color: white; border-radius: 50%;" size="30px" name="cloud-upload"></t-icon>
        </file-upload>
        <div class="name">{{formData.nickName}}</div>
        <div class="position">{{formData.duty}}</div>
      </t-card>
      <t-card class="step-card" size="small" title="电子签名">
        <div style="margin-top: 10px">
          <t-popup trigger="click">
            <!--                                    @click="(signDialog.open = true)"-->
            <t-button @click="openRefreshF" variant="dashed" theme="primary" >
              <t-icon :name="signatureFiles.length > 0 > 0?'edit-1':'add-circle'" slot="icon" style="margin-right: 3px"/>
              {{signatureFiles.length > 0?'更新在线签名':'添加在线签名'}}
            </t-button>
            <template #content>
              <h3>手机扫码签名</h3>
              <qrcode-vue  :value="qrcodeValue" :size="192" level="H" />

            </template>
          </t-popup>
        </div>
        <div v-if="signatureFiles.length > 0" style="margin-top: 20px">
          <img :src="signatureFiles[0].url" width="150" height="70" style="border: 2px dashed #d3d3d3;" />
        </div>
      </t-card>
    </t-col>
  </t-row>
    <reset-pwd :header="dialog.header" :visible.sync="dialog.open"
               v-if="dialog.open"></reset-pwd>
    <wechat-bind :header="dialog.header" :visible.sync="dialog.openBind"
                 v-if="dialog.openBind"></wechat-bind>
</div>
</template>

<script>
import ResetPwd from './components/reset-pwd.vue'
import WechatBind from "./components/wechat-bind.vue";
import QrcodeVue from 'qrcode.vue';
import {getToken} from "@/utils/auth";
import FileUpload from "@/components/FileUpload/index.vue";
import {getFiles} from "@/api/common"
import {getIdCardBirthday, getIdCardAge} from '@/utils/common';


export default {
  name: "center",
  dicts:['prof_tit', 'duty', "degree", "sys_user_sex", "national", "politics_status", "education", "politics_status"],
  components:{
    ResetPwd,
    WechatBind,
    QrcodeVue,
    FileUpload
  },
  data(){
    return {
      qrcodeValue: '',
      openRefresh:false,
      refreshStart: false,
      signatureFiles: [],
      dialog:{
        open: false,
        header: '',
        openBind: false
      },
      avatarFileIds: [],
      avatarFileLists: [],
      value:'first',
      formData:{
        dept:{},
        sex:'',
        birthDate:'',
        nickName:'',
        school:'',
        degree:'',
        majorName:'',
        majorNowName: '',
        postcode:'',
        phonenumber:'',
        email:'',
        wechat:'',
        national:'',
        duty:'',
        profTit:'',
        roleIds:'',
        remark: '',
        education: '',
        idCard: '',
        politicsStatus: '',
        contactAds: '',
        profTitId: null,
        avatar: '',
      },
      rules:{
        nickName: [
          {
            required: true,
            message: "真实姓名不能为空",
          },
        ],
        email: [
          {
            required: true,
            message: "邮箱不能为空",
          },
          {email: {ignore_max_length: true}, message: '请输入正确的邮箱地址'}
        ],
        idCard: [
          {
            message: "身份证号不正确",
            pattern: /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/,
          },
        ],
        phonenumber: [
          {
            required: true,
            message: "手机号不能为空",
          },
          {
            pattern: /^(?:(?:\+|00)86)?1\d{10}$/,
            message: '请输入正确的手机号',
            type: 'error',
            trigger: 'blur'
          },
        ]
      },
      roleOptions: [],
      profTitOptions: [],
      signDialog: {
        open: false,
        signId: 0,
        file: {}
      },
      timer: null,
    }
  },
  created() {
    this.qrcodeValue = `${window.location.origin}/online-signature/?code=${getToken()}`;
    this.getInfo();
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  methods:{
    openRefreshF(){
      this.timer = setInterval(this.refreshFile, 1000);
    },
    onIdCardChange(val) {
      const birthday = getIdCardBirthday(val);
      if (birthday !== "") {
        this.formData.birthDate = birthday
      }
    },
    onProfTitIdChange(val){
      this.$api.system.profTit.get(val).then(response => {
        this.formData.profTit = response.data.level;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    updateUserProfile({validateResult, firstError}){
      if (validateResult === true) {
        this.$api.system.user.updateUserProfile({
          sex: this.formData.sex,
          birthDate: this.formData.birthDate,
          nickName: this.formData.nickName,
          school: this.formData.school,
          degree: this.formData.degree,
          majorName: this.formData.majorName,
          majorNowName: this.formData.majorNowName,
          postcode: this.formData.postcode,
          phonenumber: this.formData.phonenumber,
          email: this.formData.email,
          wechat: this.formData.wechat,
          national: this.formData.national,
          duty: this.formData.duty,
          profTit: this.formData.profTit,
          remark: this.formData.remark,
          idCard: this.formData.idCard,
          education: this.formData.education,
          politicsStatus: this.formData.politicsStatus,
          contactAds: this.formData.contactAds,
          profTitId: this.formData.profTitId,
        }).then(response => {
          this.$message.success("保存成功");
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      }else {
        this.$message.error(firstError);
      }
    },
    refreshFile(){
      this.refreshStart = true;
      getFiles(this.formData.id).then((res) => {
        const files = {}
        res.data.forEach((item) => {
          if (!files[item.moduleKey]) {
            files[item.moduleKey] = []
          }
          files[item.moduleKey].push({
            name: item.fileName,
            url: item.fullFilePath,
            id: item.id,
            filePath: item.filePath
          })
        })
        // if (files.signature && files.signature.length > 1) {
        //   files.signature.reverse()
        // }
        this.signatureFiles = files.signature || []
        this.refreshStart = false;
      }).catch(e => {
        this.refreshStart = false;
        this.$message.error(e.toString())
      })
    },
    getInfo(){
      Promise.all([this.$api.system.profTit.treeselect()]).then(res => {
        this.profTitOptions = res[0].data;
        this.$api.system.user.getBaseInfo().then(response => {
          this.formData = response.data;
          this.formData.roleIds = response.data.roles.map((val)=>val.roleName).join(",")
          getFiles(this.formData.id).then((res) => {
            const files = {}
            res.data.forEach((item) => {
              if (!files[item.moduleKey]) {
                files[item.moduleKey] = []
              }
              files[item.moduleKey].push({
                name: item.fileName,
                url: item.fullFilePath,
                id: item.id,
                filePath: item.filePath
              })
            })
            // if (files.signature && files.signature.length > 1) {
            //   files.signature.reverse()
            // }
            this.signatureFiles = files.signature || []
            this.refreshStart = false;
          }).catch(e => {
            this.refreshStart = false;
            this.$message.error(e.toString())
          })
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getSignFile(file) {
      if (file.id) {
        this.$api.system.user.updateUserProfile({
          sysAttMainVo: {
            sysAttMainIds: [file.id]
          }
        }).then(response => {
          this.signatureFiles = [{
            name: file.fileName,
            url: file.fullFilePath,
            id: file.id,
            filePath: file.filePath
          }]
          this.$message.success('签名上传成功！')
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      } else {
        this.$message.error('签名上传失败！')
      }
    },
    onAvatar(ids,files){
      this.$api.system.user.updateUserProfile({
        avatar: files[0].url,
      }).then(response => {
        this.formData.avatar = files[0].url;
        this.$message.success("上传成功");
      }).catch((e) => {
        this.$message.error(e.toString());
      });

    },
  }
}
</script>

<style lang="less" scoped>
@import url('./center.less');
.step-card{
  margin-bottom: 14px;
}
/deep/ .t-upload__tips-error{
  display: none;
}
</style>
